import React, { Component } from 'react';
import {
  View, Text, StyleSheet, TouchableOpacity, Image, Dimensions, TextInput, ScrollView,
  PixelRatio, ActionSheetIOS, Platform, Keyboard, Modal, Alert, DeviceEventEmitter
} from 'react-native';

import { GLOBAL } from '../../../../../config/global';
import { style } from '../../../../../theme/style';
import { MapView, MapTypes, Geolocation } from 'react-native-baidu-map';
import { PageStatusIndex } from '../../../../../component/page-status/PageStatusIndex';
import { Common } from '../../../../../component/common/Common';

const scale = GLOBAL.SCALE;

let curCity = '';
let curAddress = '';
const searchIcon = require('../../../../../imgs/global/whiteSearch.png');
const searchIconStyle = { width: 26 * scale, resizeMode: 'contain', marginRight: 10 * scale };

export class Address extends Component {
  static navigationOptions = ({ navigation }) => {
    return {
      headerTitle: '请选择地址',
      headerTintColor: style.color.white,
      headerLeft: <Common type="headLeft" onPress={() => { navigation.goBack() }} color='#fff' />,
      headerRight: (<Image style={{ marginLeft: 18 * scale, width: 9 * scale, height: 16 * scale }} source={require('../../../../../imgs/goBackEmpty.png')} />),
      headerStyle: style.head.headerStyle,
      headerTitleStyle: {
        flex: 1,
        textAlign: 'center',
      }
    }
  };

  constructor(props) {
    super(props);
    this.state = {
      pageStatus: {
        status: 'loading'
      },
      mayType: MapTypes.NORMAL,
      zoom: 15,
      trafficEnabled: false,
      baiduHeatMapEnabled: false,
      keyboard: false,
      markers: [],
      center: {},
    };
    this.addressCodeParam = {}

    this._setSelectAddress = this._setSelectAddress.bind(this);
    this.goToAddressList = this.goToAddressList.bind(this);

    // this.goBackPage = this.props.navigation.state.params.goBackPage;
  }

  componentWillMount () {
    this.keyboardDidShowListener = Keyboard.addListener('keyboardDidShow', this._keyboardDidShow.bind(this));
    this.keyboardDidHideListener = Keyboard.addListener('keyboardDidHide', this._keyboardDidHide.bind(this));

    DeviceEventEmitter.addListener('CheckAddressItem', (dic) => {
      const { params } = this.props.navigation.state;
      //接收到前一页发送的通知，刷新数据，刷新UI
      if (params.selectAddress) {
        this.getReverseGeoCodeResult(Number(params.selectAddress.latitude), Number(params.selectAddress.longitude), params.selectAddress.name);
      }
    });
  }

  componentWillUnmount () {
    try {
      this.keyboardDidShowListener.remove();
      this.keyboardDidHideListener.remove();
    } catch (error) {
      console.log(error);
    }
  }

  _keyboardDidShow () {
    this.setState({ keyboard: true });
  }

  _keyboardDidHide () {
    this.setState({ keyboard: false });
  }

  componentDidMount () { // 获取位置
    const { addressCodeParam } = this.props.navigation.state.params || {};

    if (addressCodeParam && addressCodeParam.latitude) {
      // addressObj.latitude = addressObj.latitude;
      // addressObj.longitude = addressObj.longitude;
      this._setSelectAddress(addressCodeParam);
    } else {
      this.getCurrentPosition();
    }

    // this.props.navigation.setParams({
    //   setSelectAddress: this._setSelectAddress,
    //   goToAddressList: this.goToAddressList,
    // });
  }

  _setSelectAddress (selectAddress) {
    const { longitude, latitude, city, district, poiInfo, name, address, streetName } = selectAddress;
    this.addressCodeParam = selectAddress;
    curAddress = poiInfo;
    curCity = city;
    this.setState({
      pageStatus: {
        status: 'data'
      },
      zoom: 18,
      markers: [{
        latitude: Number(latitude),
        longitude: Number(longitude),
        address: address,
        city: city,
        district: district,
        title: '位置:' + poiInfo,
        poiInfo: name || poiInfo,
        streetName
      }],
      center: {
        latitude: Number(latitude),
        longitude: Number(longitude),
      },
    });
    if (latitude && longitude) {
      this.getReverseGeoCodeResult(Number(latitude), Number(longitude), name || poiInfo);
    }
  }

  //获取地理位置
  getCurrentPosition () {
    Geolocation.getCurrentPosition().then(
      (data) => {
        console.log("getCurrentPosition:" + JSON.stringify(data));
        this.setData(data);
      }
    ).catch(error => {
      this.setState({
        pageStatus: {
          status: 'error',
          onErrorPress: () => {
            this.setState({
              pageStatus: {
                status: 'loading'
              }
            })
            this.getCurrentPosition();
          }
        },
      })
      console.log(error, 'error')
    })
  }

  // 经纬度位置转换具体地址
  getReverseGeoCodeResult (latitude, longitude, listItem) {
    Geolocation.reverseGeoCode(latitude, longitude, listItem).then(
      (data) => {
        console.log("getReverseGeoCodeResult:" + JSON.stringify(data));
        this.setData(data, latitude, longitude, listItem);
      }
    ).catch(error => {
      this.setState({
        pageStatus: {
          status: 'error',
          onErrorPress: () => {
            this.setState({
              pageStatus: {
                status: 'loading'
              }
            })
            this.getReverseGeoCodeResult(Number(latitude), Number(longitude), listItem);
          }
        },
      })
    })
  }

  setData (data, latitude, longitude, listItem) {
    this.setState({
      pageStatus: {
        status: 'data'
      },
      zoom: 18,
      markers: [{
        latitude: latitude || data.latitude,
        longitude: longitude || data.longitude,
        province: data.province,
        city: data.city,
        district: data.district,
        address: data.address,
        title: '位置:' + data.address,
        poiInfo: listItem || data.poiInfo,
        streetName: data.streetName
      }],
      center: {
        latitude: latitude || data.latitude,
        longitude: longitude || data.longitude
      },
    });
    this.addressCodeParam = {
      latitude: latitude || data.latitude,
      longitude: longitude || data.longitude,
      province: data.province,
      city: data.city,
      district: data.district,
      address: data.address,
      poiInfo: listItem || data.poiInfo,
      streetName: data.streetName
    }
    console.log(150, data);
    curCity = data.city;
    curAddress = data.poiInfo;
  }

  goToAddressList () {
    const curAddressStr = (this.addressCodeParam.poiInfo) ? this.addressCodeParam.poiInfo : curAddress
    this.props.navigation.navigate("AddressListPage", {
      curCity: this.addressCodeParam.city,
      curAddress: curAddressStr,
      addressObj: this.addressCodeParam
    })
  }

  render () {
    const { params } = this.props.navigation.state;
    const { markers, pageStatus, keyboard } = this.state;
    let { province, city, streetName, address, poiInfo } = markers[0] || {};
    let addressText = `${province || ''}${city || ''}${streetName || ''}`;
    const inputsCellTop = { bottom: Platform.OS === 'ios' ? (keyboard ? 280 * scale : 5 * scale) : 5 * scale };

    return (
      <View style={styles.container}>
        {
          pageStatus.status === 'data' ? (
            <View style={styles.container}>
              <MapView
                trafficEnabled={this.state.trafficEnabled}
                baiduHeatMapEnabled={this.state.baiduHeatMapEnabled}
                zoom={this.state.zoom}
                mapType={this.state.mapType}
                center={this.state.center}
                markers={this.state.markers}
                style={styles.map}
                onMarkerClick={(e) => {
                  console.log('markerlick', e);
                }}
                onMarkerDragEnd={(e) => {
                  console.log('drag', e);
                  this.getReverseGeoCodeResult(e.position.latitude, e.position.longitude);
                }}
                onMapStatusChangeFinish={(e) => {
                  console.log('change', e);
                  this.getReverseGeoCodeResult(e.target.latitude, e.target.longitude);
                }}
                onMapClick={(e) => {//支持地图点击的时候切换改变地址
                  console.log('click', e);
                  this.getReverseGeoCodeResult(e.latitude, e.longitude);
                }}
              >
              </MapView>

              <View style={styles.location}>
                <TouchableOpacity style={styles.mapSelect}
                  activeOpacity={0.5} onPress={() => { this.getCurrentPosition(); }}>
                  <Image style={styles.locationIcon} source={require('../../../../../imgs/global/location.png')} />
                </TouchableOpacity>
              </View>
              <View style={[styles.mapInputContainer, inputsCellTop]}>
                <View style={styles.infoRow}>
                  <TouchableOpacity style={styles.mapSelect}
                  // activeOpacity={0.5} onPress={() => {
                  //   this.goToAddressList();
                  // }}
                  >
                    <View style={styles.infoRowLeft}><Image style={styles.iconLeft} source={require('../../../../../imgs/global/position.png')} /></View>
                    <View style={styles.infoCenter}><Text style={styles.infoCenterText}>{addressText || '请选择'}</Text></View>
                    {/* <View style={styles.infoRowRight}><Image style={styles.iconRight} source={require('../../../../../imgs/arrow-left.png')} /></View> */}
                  </TouchableOpacity>
                </View>
                <View style={styles.infoRow}>
                  <TextInput
                    style={styles.textInput}
                    placeholder={'请输入详细地址'}
                    underlineColorAndroid='transparent'
                    // maxLength={30}
                    defaultValue={markers[0].poiInfo}
                    onChangeText={(txt) => {
                      this.addressCodeParam.poiInfo = txt;
                    }}
                    onBlur={() => {
                      this._setSelectAddress(this.addressCodeParam)
                    }}
                  />
                </View>
                <View style={styles.submitBtnCell}>
                  <TouchableOpacity activeOpacity={0.5} style={styles.submitBtn}
                    onPress={() => {
                      this.props.navigation.navigate('NewMaintenance', {
                        addressCodeParam: this.addressCodeParam,
                      })

                    }} >
                    <Text style={styles.submitBtnText}>确定</Text>
                  </TouchableOpacity>
                </View>
              </View>
            </View>) : (<PageStatusIndex {...pageStatus} />)   //页面加载状态
        }

      </View>
    );
  }

}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    flexDirection: 'row',
    justifyContent: 'flex-start',
  },
  map: {
    flex: 1,
  },
  location: {
    flex: 1,
    position: 'absolute',
    right: 6 * scale,
    bottom: 185 * scale,
  },
  mapInputContainer: {
    backgroundColor: '#fff',
    width: 365 * scale,
    position: 'absolute',
    left: 5 * scale,
    bottom: 8 * scale,
  },
  infoRow: {
    width: 365 * scale,
    height: 52 * scale,
    marginLeft: 5 * scale,
    paddingRight: 5 * scale,
    borderBottomColor: '#e4e4e4',
    borderBottomWidth: 1 / PixelRatio.get(),
    flexDirection: 'row',
    alignItems: 'center',
    flexWrap: 'wrap'
  },
  mapSelect: {
    flex: 1,
    flexDirection: 'row',
  },
  infoRowLeft: {
    justifyContent: 'center',
    height: 52 * scale,
    marginLeft: 6 * scale,
  },
  infoCenter: {
    justifyContent: 'center',
    height: 52 * scale,
    flex: 1
  },
  infoCenterText: {
    fontSize: 13 * scale,
    color: '#404040',
  },
  infoRowRight: {
    justifyContent: 'center',
    height: 52 * scale,
  },
  iconLeft: {
    height: 16 * scale,
    width: 10 * scale,
    marginRight: 5 * scale,
  },
  iconRight: {
    height: 12 * scale,
    width: 6 * scale,
    marginRight: 5 * scale,
  },
  textInput: {
    borderWidth: 0,
    fontSize: 13 * scale,
    color: '#8B8B8B',
    width: '100%',
    height: 18 * scale,
    padding: 0,
    marginLeft: 18 * scale,
  },
  submitBtnCell: {
    width: '100%',
    justifyContent: 'center',
    alignItems: 'center',
    marginTop: 10 * scale,
    marginBottom: 10 * scale,
  },
  submitBtn: {
    justifyContent: 'center',
    alignItems: 'center',
    width: '94%',
    height: 44 * scale,
    borderRadius: 100,
    backgroundColor: style.color.themeColor,
  },
  submitBtnText: {
    color: '#fff',
    fontSize: 18 * scale,
  },
})